package cn.ulyer.core.modules.system.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.ulyer.common.jpa.entity.Group;
import cn.ulyer.common.jpa.entity.GroupRole;
import cn.ulyer.common.jpa.entity.QGroup;
import cn.ulyer.common.jpa.entity.QGroupRole;
import cn.ulyer.common.jpa.service.AbstractService;
import cn.ulyer.core.modules.system.repository.GroupRoleRepository;
import cn.ulyer.core.modules.system.service.TGroupService;
import com.querydsl.jpa.impl.JPAQuery;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;


@Service
public class TGroupServiceImpl extends AbstractService<Group,Integer> implements TGroupService {


    @Override
    protected JPAQuery<Group> buildPageQuery(Object queryModel) {
        Group group = (Group) queryModel;
        QGroup qGroup = QGroup.group;
        JPAQuery<Group> typeQuery = jpaQueryFactory.selectFrom(qGroup);
        if(group!=null){
            if(StrUtil.isNotBlank(group.getName())){
                typeQuery.where(qGroup.name.eq(group.getName()));
            }
            if(group.getStatus()!=null){
                typeQuery.where(qGroup.status.eq(group.getStatus()));
            }
        }
        return typeQuery;
    }

    @Resource
    private GroupRoleRepository groupRoleRepository;


    @Override
    public void bindRoles(List<Integer> roles, Integer groupId) {
        QGroupRole qGroupRole = QGroupRole.groupRole;
        jpaQueryFactory.delete(qGroupRole).where(qGroupRole.groupId.eq(groupId));
        if(roles!=null){
            List<GroupRole> groupRoles = new LinkedList<>();
            roles.forEach(r->{
                GroupRole g = new GroupRole();
                g.setGroupId(groupId);
                g.setRoleId(r);
                groupRoles.add(g);
            });
            groupRoleRepository.saveAll(groupRoles);
        }
    }
}
